﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;


namespace DATN.Account
{
    public partial class Login : System.Web.UI.Page
    {
        SqlConnection cnn;
        SqlCommand cmd;
        string username = "";
        int usid;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] != null && Session["Us_Id"] != null)
                {
                    username = Session["UserName"].ToString();
                    usid = Convert.ToInt16(Session["Us_Id"].ToString());

                    if (check_User(Session["UserName"].ToString()) == 1)
                    {
                        //check role
                        if (check_Role(usid) == 1) 
                        {
                            Response.Redirect("~/Administrator/Admin.aspx");
                        }
                        else if (check_Role(usid) == 2)
                        {
                            Response.Redirect("~/mds.UserInterface/InternalIndex.aspx");
                        }
                    }
                    else
                    {
                        LabelLogin.Text = "Ban dinh cheat voi Session o day!! ";
                    }
                }
        }

        //Check id - nhập UserName sẽ trả lại Us_Id
        int ChId;
        protected int check_Id(string UserName)
        {
            ChId = 0;
            try{
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Us_Id FROM Users WHERE UserName = @username";
                   
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@username", SqlDbType.VarChar);
                cmd.Parameters["@username"].Value = UserName;

                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    ChId = Convert.ToInt32(reader["Us_Id"].ToString());
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write(" Lỗi ở Check User ID: "+ ex);
                cnn.Close();
            }

            return ChId;
        }

        //Check UserName: Kiem tra UserName có hay ko
        int ChUs;
        protected int check_User(string username)
        {
            ChUs = 0;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Count(*) FROM Users WHERE UserName=@username";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@username", SqlDbType.VarChar);
                cmd.Parameters["@username"].Value = username;

                ChUs = Convert.ToInt32(cmd.ExecuteScalar().ToString());

            }catch(Exception ex)
            {
                Response.Write(" Lỗi ở Check UserName: "+ ex);
            }
            return ChUs;
        }
        
        //Check Role: Khi nhét Us_Id vào
        int ChRole;
        protected int check_Role(int Us_Id)
        {
            ChRole = 0;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Ro_Id FROM UserRole WHERE Us_Id = @us_id";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@us_id", SqlDbType.VarChar);
                cmd.Parameters["@us_id"].Value = Us_Id;

                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    ChRole = Convert.ToInt32(reader["Ro_Id"].ToString());
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Error Check Role: " + ex);
                cnn.Close();
            }
            finally {
                cnn.Close();
            }

            return ChRole;
        }

        //check user password:
        int ChUsPas;
        protected int check_UserPass(string username, string password)
        {
            ChUsPas = 0;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Count(*) FROM Users WHERE UserName=@UserName AND Password =@Password ";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@UserName", SqlDbType.VarChar);
                cmd.Parameters["@UserName"].Value = username;

                cmd.Parameters.Add("@Password", SqlDbType.VarChar);
                cmd.Parameters["@Password"].Value = Encrypt.EncryptText(password, true);

                ChUsPas = Convert.ToInt32(cmd.ExecuteScalar().ToString());
            }
            catch (Exception ex)
            {
                Response.Write(" Lỗi ở Check UserName: " + ex);
            }
            return ChUsPas;
        }
        
        //Click vao button
        protected void LoginButton_Click(object sender, EventArgs e)
        { 
            if (tbx_UserName.Text != "" && tbx_Password.Text != "")
            {
                int UserId = check_Id(tbx_UserName.Text);
                //Check username co hay ko
                if (check_User(tbx_UserName.Text) == 1)
                {
                    //check User and Password
                    if (check_UserPass(tbx_UserName.Text, tbx_Password.Text) == 1)
                    {
                        //check role
                        if (check_Role(UserId) == 1)
                        {
                            Session["Us_Id"] = UserId;
                            Session["UserName"] = tbx_UserName.Text;
                            Response.Redirect("~/Administrator/Admin.aspx");
                        }
                        else if (check_Role(UserId) == 2)
                        {
                            Session["Us_Id"] = UserId;
                            Session["UserName"] = tbx_UserName.Text;
                            Response.Redirect("~/mds.UserInterface/InternalIndex.aspx");
                        }
                    }
                    else
                    {
                        LabelLogin.Text = "Sai mật khẩu";
                    }   
                }
                else
                {
                    LabelLogin.Text = " Tên đăng nhập không tồn tại! ";
                }
            }
            else 
            {
                LabelLogin.Text = "Nhập thông tin vào cả 2 ô trên. ";
            }
        }
    }
}